﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Globalization;
using Sherwood.SignOn.Server.Models.Repositories;
using Sherwood.SignOn.Server.Models.Services;

namespace Sherwood.SignOn.Server.Models.ViewModels
{
    /// <summary>
    /// View model for /UserAccount/DontChangePassword action
    /// </summary>
    public class DontChangePasswordViewModel : ViewModelBase
    {
        public string UserAccountId { get; set; }
        public string VerificationCode { get; set; }
        public DontChangePasswordResult Result { get; set; }

        public enum DontChangePasswordResult
        {
            NoRequest,
            Failure,
            Success
        }

        /// <summary>
        /// Attempts to reverse a password change request (so that the original password is maintained)
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public bool DontChangePassword(ModelStateDictionary state)
        {
            if (!string.IsNullOrEmpty(UserAccountId) && !string.IsNullOrEmpty(VerificationCode))
            {
                IUserAccount account = Data.UserAccounts.GetUserAccount(new Guid(UserAccountId));
                if (account != null)
                {
                    if (account.VerificationStatus != VerificationStatus.ResetPassword)
                    {
                        Result = DontChangePasswordResult.NoRequest;
                        return false;
                    }
                    else
                    {
                        if (account.ValidateVerificationCode(VerificationCode))
                        {
                            //Verify account, but don't reset password.
                            account.SetVerificationParameters(VerificationStatus.Verified,null,null);
                            Result = DontChangePasswordResult.Success;
                            return true;
                        }
                    }
                }
                else
                {
                    //Account not found
                    Result = DontChangePasswordResult.Failure;
                    return false;
                }
            }

            //Invalid request (no useraccountid or verification code provided)
            Result = DontChangePasswordResult.Failure;
            return false;
        }
    }
}
